//
//  QuickLoansStep1View.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/12/6.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

@objc protocol QuickLoansStep1ViewDelegate {
    @objc optional func nextStepAction() //下一步
}

class QuickLoansStep1View: UIView {
    
    weak var delegate : QuickLoansStep1ViewDelegate?
    
    fileprivate let scrollView = UIScrollView()
    
    fileprivate let titleLabel = UILabel()
    fileprivate let lineView = UIView()
    fileprivate let nameView = LoanSelectView.init(firstText: man, lastText: woman) //姓名
    fileprivate let workView = LoanScreenView() //职业
    fileprivate let ageView = LoanSelectView() //年龄
    fileprivate let incomeView = LoanScreenView() //收入
    fileprivate let cardNumberView = LoanSelectView() //身份证号
    fileprivate let provinceView = LoanScreenView() //省份
    fileprivate let cityView = LoanScreenView() //城市
    fileprivate let loanAmountView = LoanScreenView() //贷款金额
    fileprivate let loanTermView = LoanScreenView() //贷款时间
    fileprivate let loanUseView = LoanScreenView() //贷款用途
    fileprivate let creditCardView = LoanSelectView() //信用卡
    fileprivate let securityView = LoanSelectView() //社保
    fileprivate let providentView = LoanSelectView() //公积金
    
    fileprivate let nextButton = UIButton() //下一步
    fileprivate let labelTypeView = QuickLoanSelectView() //标签类型选择
    fileprivate var preLoanSelectView = LoanScreenView() //记录上一个点击的按钮
    
    fileprivate var curProvince = "" //当前省份
    var model = [String:String]() //相关数据

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        scrollView.showsVerticalScrollIndicator = false
        scrollView.bounces = false
        scrollView.delegate = self
        self.addSubview(scrollView)
        
        titleLabel.text = "step 1 > " + basicInfo
        titleLabel.textColor = UIColor.red
        titleLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 18))
        scrollView.addSubview(titleLabel)
        
        lineView.backgroundColor = UIColor.red
        scrollView.addSubview(lineView)
        
        nameView.title = name
        nameView.placeholder = inputName
        nameView.isHide = false
        nameView.tag = 1
        nameView.delegate = self
        scrollView.addSubview(nameView)
        
        workView.tag = 1
        workView.title = occupational
        workView.delegate = self
        workView.placeholder = selectOccupational
        scrollView.addSubview(workView)
        
        ageView.title = age
        ageView.showSelect = false
        ageView.isHide = false
        ageView.placeholder = inputAge
        ageView.textField.keyboardType = .numberPad
        ageView.tag = 2
        ageView.delegate = self
        scrollView.addSubview(ageView)
        
        incomeView.tag = 2
        incomeView.title = income
        incomeView.placeholder = selectIncome
        incomeView.delegate = self
        scrollView.addSubview(incomeView)
        
        cardNumberView.title = idNumber
        cardNumberView.isHide = false
        cardNumberView.showSelect = false
        cardNumberView.placeholder = inputCardNumber
        cardNumberView.textField.keyboardType = .asciiCapable
        cardNumberView.tag = 3
        cardNumberView.delegate = self
        scrollView.addSubview(cardNumberView)
        
        provinceView.tag = 3
        provinceView.title = whichProvince
        provinceView.placeholder = selectProvince
        provinceView.delegate = self
        scrollView.addSubview(provinceView)
        
        cityView.tag = 4
        cityView.title = whichCity
        cityView.placeholder = selectToCity
        cityView.delegate = self
        scrollView.addSubview(cityView)
        
        loanAmountView.tag = 5
        loanAmountView.title = loanAmount
        loanAmountView.placeholder = selectLoanAmount
        loanAmountView.delegate = self
        scrollView.addSubview(loanAmountView)
        
        loanTermView.tag = 6
        loanTermView.title = durationLoan
        loanTermView.placeholder = selectdurationLoan
        loanTermView.delegate = self
        scrollView.addSubview(loanTermView)
        
        loanUseView.tag = 7
        loanUseView.title = loanUse
        loanUseView.placeholder = selectLoanUse
        loanUseView.delegate = self
        scrollView.addSubview(loanUseView)
        
        creditCardView.title = hasCreditCard
        creditCardView.tag = 4
        creditCardView.delegate = self
        scrollView.addSubview(creditCardView)
        
        securityView.title = hasSocialSecurity
        securityView.tag = 5
        securityView.delegate = self
        scrollView.addSubview(securityView)
        
        providentView.title = hasProvidentFund
        providentView.tag = 6
        providentView.delegate = self
        scrollView.addSubview(providentView)
        
        nextButton.setTitle(nextStep, for: .normal)
        nextButton.backgroundColor = UIColor.red
        nextButton.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        nextButton.layer.cornerRadius = 5
        nextButton.layer.masksToBounds = true
        nextButton.addTarget(self, action: #selector(nextSeptAction), for: .touchUpInside)
        scrollView.addSubview(nextButton)
        
        labelTypeView.isHidden = true
        labelTypeView.delegate = self
        scrollView.addSubview(labelTypeView)
        
        scrollView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(20)
            make.centerX.equalToSuperview()
            make.height.greaterThanOrEqualTo(10)
            make.width.greaterThanOrEqualTo(10)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.equalTo(self).offset(RATIO(maxNum: 10))
            make.right.equalTo(self).offset(RATIO(maxNum: -10))
            make.top.equalTo(titleLabel.snp.bottom).offset(5)
            make.height.equalTo(1)
        }
        
        nameView.snp.makeConstraints { (make) in
            make.top.equalTo(lineView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(40)
        }
        
        workView.snp.makeConstraints { (make) in
            make.top.equalTo(nameView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(nameView)
        }
        
        ageView.snp.makeConstraints { (make) in
            make.top.equalTo(workView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(workView)
        }
        
        incomeView.snp.makeConstraints { (make) in
            make.top.equalTo(ageView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(ageView)
        }
        
        cardNumberView.snp.makeConstraints { (make) in
            make.top.equalTo(incomeView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(incomeView)
        }
        
        provinceView.snp.makeConstraints { (make) in
            make.top.equalTo(cardNumberView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(cardNumberView)
        }
        
        cityView.snp.makeConstraints { (make) in
            make.top.equalTo(provinceView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(provinceView)
        }
        
        loanAmountView.snp.makeConstraints { (make) in
            make.top.equalTo(cityView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(cityView)
        }
        
        loanTermView.snp.makeConstraints { (make) in
            make.top.equalTo(loanAmountView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(loanAmountView)
        }
        
        loanUseView.snp.makeConstraints { (make) in
            make.top.equalTo(loanTermView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(loanTermView)
        }
        
        creditCardView.snp.makeConstraints { (make) in
            make.top.equalTo(loanUseView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(loanUseView)
        }
        
        securityView.snp.makeConstraints { (make) in
            make.top.equalTo(creditCardView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(80)
        }
        
        providentView.snp.makeConstraints { (make) in
            make.top.equalTo(securityView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(securityView)
        }
        
        nextButton.snp.makeConstraints { (make) in
            make.top.equalTo(providentView.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
            make.width.equalTo(ScreenW/3)
            make.height.equalTo(40)
        }
        
        self.layoutIfNeeded()
        scrollView.contentSize = .init(width: ScreenW, height: nextButton.frame.maxY + 20 + StatusBarAddNavBarHeight)
    }
    
    //MARK: 下一步
    @objc fileprivate func nextSeptAction() {
        
        if nameView.text == "" || nameView.text == nil {
            KMTool.showText(_text: inputName)
            return
        }

        if nameView.isYes == "" {
            KMTool.showText(_text: selectSex)
            return
        }

        if workView.text == "" || workView.text == nil {
            KMTool.showText(_text: selectOccupational)
            return
        }

        if ageView.text == "" || ageView.text == nil {
            KMTool.showText(_text: inputAge)
            return
        }

        if incomeView.text == "" || incomeView.text == nil {
            KMTool.showText(_text: selectIncome)
            return
        }

        if cardNumberView.text == "" || cardNumberView.text == nil {
            KMTool.showText(_text: inputCardNumber)
            return
        }

        if provinceView.text == "" || provinceView.text == nil {
            KMTool.showText(_text: selectProvince)
            return
        }

        if cityView.text == "" || cityView.text == nil {
            KMTool.showText(_text: selectCity)
            return
        }

        if loanAmountView.text == "" || loanAmountView.text == nil {
            KMTool.showText(_text: selectLoanAmount)
            return
        }

        if loanTermView.text == "" || loanTermView.text == nil {
            KMTool.showText(_text: selectdurationLoan)
            return
        }

        if loanUseView.text == "" || loanUseView.text == nil {
            KMTool.showText(_text: selectLoanUse)
            return
        }

        if creditCardView.isYes == "" {
            KMTool.showText(_text: hasCreditCard)
            return
        }

        if securityView.isYes == "" {
            KMTool.showText(_text: hasSocialSecurity)
            return
        }

        if providentView.isYes == "" {
            KMTool.showText(_text: hasProvidentFund)
            return
        }
        
        if !checkIdNumber() {
            KMTool.showText(_text: inputRightCardNumber)
            return
        }
        
        
        self.delegate?.nextStepAction!()
    }
    
    //MARK: 身份证验证
    fileprivate func checkIdNumber() -> Bool {
        
        if cardNumberView.text.count != 18 {
            return false
        }
        
        //校检格式
        let regex = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$"
        let identityCardPredicate = NSPredicate.init(format: "SELF MATCHES %@", regex)
        let flag = identityCardPredicate.evaluate(with: cardNumberView.text)
        if !flag {
            return flag //格式错误
        }else{
            //格式正确在判断是否合法
            
            //将前17位加权因子保存在数组里
            let idCardWiArray = ["7","9","10","5","8","4","2","1","6","3","7","9","10","5","8","4","2"]
            //这是除以11后，可能产生的11位余数、验证码，也保存成数组
            let idCardYArray = ["1","0","10","9","8","7", "6", "5","4","3","2"]
            //用来保存前17位各自乖以加权因子后的总和
            var idCardWiSum = 0
            
            for i in 0..<17 {
                let subStrIndex = Int((cardNumberView.text as NSString?)?.substring(with: NSMakeRange(i, 1)) ?? "0")
                let idCardWiIndex = Int(idCardWiArray[i])
                idCardWiSum += subStrIndex! * idCardWiIndex!
                
            }
            
            //计算出校验码所在数组的位置
            let idCardMod = idCardWiSum%11
            
            //得到最后一位身份证号码
            let idCardLast = (cardNumberView.text as NSString?)?.substring(with: NSMakeRange(17, 1))
            //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
            if idCardWiSum == 2 {
                if idCardLast == "X" || idCardLast == "x" {
                    return true
                }else{
                    return false
                }
            }else{
                //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                if idCardLast == idCardYArray[idCardMod] {
                    return true
                }else{
                    return false
                }
            }
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    

}

extension QuickLoansStep1View : LoanSelectViewDelegate {
    
    //MARK: 获取输入内容
    func getInputText(currentView: LoanSelectView) {
        
        switch currentView.tag {
        case 1: //姓名
            model["name"] = currentView.text
        case 2: //年龄
            model["age"] = currentView.text
        case 3: //身份证号码
            model["IDcard"] = currentView.text
        default:
            break
        }
    }
    
    //MAKR: 选择是否
    func selectLoanType(currentView: LoanSelectView) {
        
        self.endEditing(true) //隐藏键盘
        
        switch currentView.tag {
        case 1: //性别
            if currentView.isYes == "1" {
                model["sex"] = man
            }else{
                model["sex"] = woman
            }
        case 4: //是否有信用卡
            if currentView.isYes == "1" {
                model["credit_card"] = yes_title
            }else{
                model["credit_card"] = no_title
            }
        case 5: //是否有社保
            if currentView.isYes == "1" {
                model["social_security"] = yes_title
            }else{
                model["social_security"] = no_title
            }
        case 6: //是否有公积金
            if currentView.isYes == "1" {
                model["funds"] = yes_title
            }else{
                model["funds"] = no_title
            }
        default:
            break
        }
    }
}

extension QuickLoansStep1View : LoanScreenViewDelegate,QuickLoanSelectViewDelegate {
    
    //MARK: 选择标签
    func selectLabelType(currentView: LoanScreenView) {
        
        self.endEditing(true) //隐藏键盘
        
        labelTypeView.selectType = "\(currentView.tag)"
        
        if preLoanSelectView != currentView {
            preLoanSelectView.showSelect = false
            preLoanSelectView = currentView
        }
        
        currentView.showSelect = !currentView.showSelect
        
        if currentView.showSelect {
            labelTypeView.isHidden = false
        }else{
            labelTypeView.isHidden = true
        }
        
        
        
        switch currentView.tag {
        case 1: //职业
            labelTypeView.dataArray = [individual,freelance,working,students,businessOwners,civilServiceOrSoes]
        case 2: //收入
            labelTypeView.dataArray = ["2000以下/月","2000-3000元 /月","3000-4000元/月","4000-5000元/月","5000-1000元/月","10000以上/月"]
        case 3: //省份
            labelTypeView.dataArray = KMTool.getAllProvince()
        case 4: //城市
            labelTypeView.dataArray = KMTool.getCityForProvince(province: curProvince)
        case 5: //贷款时间
            labelTypeView.dataArray = ["3万","5万","10万","20万","50万","100万"]
        case 6: //贷款期限
            labelTypeView.dataArray = ["1-3个月","4-6个月","7到12个月","1-3年","4-10年","10年以上"]
        case 7: //贷款用途
            labelTypeView.dataArray = [businessLoan,consumerLoans,ventureCapitalLoan,buyCarLoan,buyHouseLoan,investmentLoans,renovationLoan,travelLoans,studyAbroadLoan,workingCapitalLoans]
        default:
            break
        }
        
        let height = CGFloat(labelTypeView.dataArray.count * 40) > (scrollView.contentSize.height - currentView.frame.maxY - StatusBarAddNavBarHeight - 20) ? (scrollView.contentSize.height - currentView.frame.maxY - StatusBarAddNavBarHeight - 20) :  CGFloat(labelTypeView.dataArray.count * 40)
        
        labelTypeView.snp.remakeConstraints { (make) in
            make.top.equalTo(currentView.textView.snp.bottom)
            make.left.right.equalTo(currentView.textView)
            make.height.equalTo(height)
        }
    }
    
    //MARK: 选择贷款标签类型
    func selectLoanType(selectType: String, title: String) {
        
        preLoanSelectView.showSelect = false
        labelTypeView.isHidden = true
        
        switch selectType {
        case "1": //职业
            workView.text = title
            model["job"] = workView.text
        case "2": //收入
            incomeView.text = title
            model["identity"] = incomeView.text
        case "3": //省份
            provinceView.text = title
            curProvince = title
            cityView.text = ""
            model["people_province"] = provinceView.text
            model["people_city"] = cityView.text
        case "4": //城市
            cityView.text = title
            model["people_city"] = cityView.text
        case "5": //贷款金额
            loanAmountView.text = title
            model["money"] = loanAmountView.text
        case "6": //贷款期限
            loanTermView.text = title
            model["loan_deadline"] = loanTermView.text
        case "7": //贷款用途
            loanUseView.text = title
            model["use"] = loanUseView.text
        default:
            break
        }
    }
}

extension QuickLoansStep1View : UIScrollViewDelegate {
    
    //MARK: 滑动时取消选择框
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if !labelTypeView.isHidden {
            labelTypeView.isHidden = true
            preLoanSelectView.showSelect = false
        }
    }
}
